import { Cascader, Checkbox, Col, DatePicker, Form, Input, Radio, Rate, Select, Skeleton, Slider, Switch, TreeSelect, message } from 'antd';
import React, { forwardRef, useState, useEffect } from 'react';
import './ivform.scss'
import './ivform.d'
import { setInputValue } from './inputFilter'
import Login from './login'
import moment from "moment";
import "moment/locale/zh-cn"
import axios from '../../axios'
const { Option } = Select;
const layout = {
  labelCol: { span: 2 },
  wrapperCol: { span: 16 },
};
type Props = {
  formData: FormDatas[] //表单数据---必须 ---其他地方也要用写在了index.d.ts里面
  formRule?: any //表单验证
  inline?: boolean //行内表单---默认值为false
  rowWidth?: boolean
  isInit?: boolean //是否在修改后执行初始化
  layout?: 'vertical' | 'horizontal'

}
const Ivform = forwardRef((props: Props, onref) => {
  const { formData, formRule, layout = 'horizontal' } = props
  const [formDataDom, setFormDataDom] = useState([])
  // 暴露给父组件的属性
  const currentObj = {
    setData,//设置默认值
    submitForm,//触发成功拿到表单的内容
    onReset //重置表单
  }
  // @ts-ignore
  onref.current = currentObj
  const [form] = Form.useForm();
  useEffect(() => {
    formInit()
  }, [])
  // 初始化表格配置
  async function formInit() {
    const formDataDom = []
    for (let item of formData) {
      if (item.ajax) {
        await doAjax(item, formDataDom)
      } else {
        formDataDom.push(getDom(item))
      }
    }
    setFormDataDom(state => {
      return [...formDataDom]
    })
  }
  // 获取下拉框的请求接口
  async function doAjax(item: FormDatas, formDataDom: FormDatas[]) {
    const ajax = item.ajax
    const { data } = await axios[ajax.methods]([ajax.url], ajax.data)
    item.options = ajax.callback(data)
    formDataDom.push(getDom(item))
  }
  // 获取到表格dom
  function getDom(val: FormDatas) {
    const confilg = {
      key: val.field, name: val.field, label: val.name, rules: formRule[val.field]
    }
    // 输入框
    if (['input'].includes(val.type)) {
      return (
        <Form.Item {...confilg}>
          <Input onInput={(event) => setInputValue(event, val.filter)} defaultValue={val.value} placeholder={val.placeholder || '请输入'} />
        </Form.Item>
      )
    }
    // 富文本
    if (['textarea'].includes(val.type)) {
      return (
        <Form.Item {...confilg}>
          <Input.TextArea defaultValue={val.value} placeholder={val.placeholder || '请输入'} />
        </Form.Item>
      )
    }
    // 下拉框
    if (val.type === 'select') {
      return (
        <Form.Item {...confilg}>
          <Select
            placeholder={val.placeholder || '请选择'}
            showSearch
            onChange={onGenderChange}
            allowClear

            mode={val.mode}
          >
            {val.options?.map(item => {
              return (<Option key={val.ajax ? item[val.ajax?.value] : item.value} value={val.ajax ? item[val.ajax?.value] : item.value}>{val.ajax ? item[val.ajax?.label] : item.label}</Option>)
            })}

          </Select>
        </Form.Item>
      )
    }
    // 开关
    if (val.type === 'switch') {
      return (
        <Form.Item {...confilg} valuePropName="checked">
          <Switch defaultChecked={val.value} unCheckedChildren='开启' checkedChildren="关闭" onChange={onChange} />
        </Form.Item>
      )
    }
    // 日期
    if (val.type === 'date') {
      return (
        <Form.Item {...confilg}>
          <DatePicker onChange={onChange}
            placeholder={val.placeholder || '请选择'}
            defaultValue={val.value}
          />
        </Form.Item>
      )
    }
    // 级联
    if (val.type === 'cascader') {

      return (
        <Form.Item {...confilg}>
          <Cascader
            key={val.field}
            placeholder={val.placeholder || '请选择'}
            fieldNames={val.fieldNames}
            multiple={val.multiple}
            showCheckedStrategy={Cascader.SHOW_CHILD}
            options={val.options}
          />
        </Form.Item>
      )
    }
    // 评分
    if (val.type === 'rate') {
      return (
        <Form.Item {...confilg}>
          <Rate allowClear={false} />
        </Form.Item>
      )
    }
    // 滑动输入条
    if (val.type === 'slider') {
      return (
        <Form.Item {...confilg}>
          <Slider />
        </Form.Item>
      )
    }
    // 单选框
    if (val.type === 'radio') {
      return (
        <Form.Item {...confilg}>
          <Radio.Group options={val.options} onChange={onChange} />
        </Form.Item>
      )
    }
    // 多选框
    if (val.type === 'checkbox') {
      return (
        <Form.Item {...confilg}>
          < Checkbox.Group options={val.options} onChange={onChange} />
        </Form.Item>
      )
    }
    // 树选择
    if (val.type === 'treeSelect') {

      return (
        <Form.Item {...confilg}>
          <TreeSelect
            key={val.field}
            allowClear
            placeholder={val.placeholder || '请选择'}
            treeDefaultExpandAll
            fieldNames={val.fieldNames}
            multiple={val.multiple}
            showCheckedStrategy={Cascader.SHOW_CHILD}
            treeData={val.options}
          />
        </Form.Item>
      )
    }
  }
  function onGenderChange(value: string) {
    switch (value) {
      case 'male':
        form.setFieldsValue({ note: 'Hi, man!' });
        return;
      case 'female':
        form.setFieldsValue({ note: 'Hi, lady!' });
        return;
      case 'other':
        form.setFieldsValue({ note: 'Hi there!' });
    }
  };
  // 表单所有的触发事件
  function onChange() { }
  // 提交表单
  function submitForm() {
    form.submit()
    const values = form.getFieldsValue()
    const formRuleKey = Object.keys(formRule)
    for (let val of formRuleKey) {
      if (!values[val]) {
        message.error('参数错误');
        return null
      }
    }
    for (let val of formData) {
      if (val.type === 'date') {
        const demo = moment(values[val.field]).format('YYYY-MM-DD HH:mm:ss')
        values[val.field] = new Date(demo).getTime()
      }
    }
    return values
  };
  // 重置表单
  function onReset() {
    form.resetFields();
  };
  // 设置默认值
  function setData(key, value) {
    form.setFieldsValue({
      [key]: value,
    });
  }

  return (
    <div style={{}} >
      {/* <Skeleton className={layout} paragraph={{ rows: formData.length }} active /> */}
      {/* 上面的是骨架屏 下面的是加载中 */}
      {formDataDom.length ? <Form form={form} name={layout} layout='horizontal' >
        {formDataDom.length ? formDataDom : <Login></Login>}
      </Form> : <Skeleton className={layout} title={false} active  paragraph={{ rows: formData.length }} />}
      {/* <Form form={form} name={layout} layout='horizontal' >
        {formDataDom.length ? formDataDom : <Login></Login>}
      </Form> */}
    </div>

  );
})

export default Ivform